#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
四则运算MCP服务
"""

from mcp.server.fastmcp import FastMCP
from typing import Union

# 创建MCP服务实例
mcp = FastMCP("FourArithmeticOperations")

@mcp.tool()
async def add(a: Union[int, float], b: Union[int, float]) -> Union[int, float]:
    """加法运算"""
    return a + b

@mcp.tool()
async def subtract(a: Union[int, float], b: Union[int, float]) -> Union[int, float]:
    """减法运算"""
    return a - b

@mcp.tool()
async def multiply(a: Union[int, float], b: Union[int, float]) -> Union[int, float]:
    """乘法运算"""
    return a * b

@mcp.tool()
async def divide(a: Union[int, float], b: Union[int, float]) -> Union[int, float]:
    """除法运算"""
    if b == 0:
        raise ValueError("除数不能为零")
    return a / b

@mcp.tool()
async def factorize(n: int) -> list:
    """因式分解"""
    if n < 1:
        raise ValueError("输入必须为正整数")
    
    factors = []
    # 处理2的因子
    while n % 2 == 0:
        factors.append(2)
        n = n // 2
    
    # 检查奇数因子
    i = 3
    max_factor = math.sqrt(n) + 1
    while i <= max_factor:
        while n % i == 0:
            factors.append(i)
            n = n // i
            max_factor = math.sqrt(n) + 1
        i += 2
    
    if n > 1:
        factors.append(n)
    
    return factors

@mcp.tool()
async def power(base: Union[int, float], exponent: Union[int, float]) -> Union[int, float]:
    """乘方运算"""
    return base ** exponent

@mcp.tool()
async def square_root(x: Union[int, float]) -> float:
    """开方运算"""
    if x < 0:
        raise ValueError("输入不能为负数")
    return math.sqrt(x)

if __name__ == "__main__":
    mcp.run(transport="stdio")